package io.receive;


import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author CZF
 * @create 2023-02-26 18:54
 */
public class Consumer {

    public  static MqttClient mqttClient = null;



    /**
     * 功能描述:发送消息
     * @author zhangpu
     * @date 2022/4/2
     * @param msg
     * @param topic
     */
    public static void publish(String msg, String topic) throws MqttException {

        if (mqttClient != null)
        {
            MqttMessage message = new MqttMessage(msg.getBytes());
            message.setQos(MqConfig.qos);
            //重新连接MQTT服务时，不需要接收该主题最新消息，设置retained为false
            //重新连接MQTT服务时，需要接收该主题最新消息，设置retained为true;
            message.setRetained(true);
            mqttClient.publish(topic, message);
        }

    }

    private static void subMsg(String clientId, String topic) throws MqttException{
        if(mqttClient != null)
        {
            int[] Qos  = {MqConfig.qos};
            String[] topics = {topic};
            mqttClient.subscribe(topics, Qos);
        }
        mqttClient.subscribe(topic,MqConfig.qos,new SubMessageListener());
    }

    public static void main(String[] args) throws MqttException {
        mqttClient = MqUtils.connect(MqConfig.broker, UUID.randomUUID().toString());

        if(mqttClient.isConnected()){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    System.out.println("启动监听成功！时间："+simpleDateFormat.format(new Date()));
                    while (true){
                        if(!mqttClient.isConnected()){

                            System.out.println("连接断开时间："+simpleDateFormat.format(new Date()));
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }).start();

            System.out.println("连接成功");
            subMsg(UUID.randomUUID().toString(), MqConfig.topic);
        }else {
            System.out.println("连接失败");
        }
        /*if (mqttClient != null)
        {
            mqttClient.disconnect();//释放连接
        }*/


    }
}
